<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-goods"></i>
          商城商品
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-form :inline="true" :model="search" class="search-form">
          <el-form-item label="商品名称">
            <el-input
              v-model="search.name"
              placeholder="商品名称"
              class="handle-input"
            />
          </el-form-item>
          <el-form-item label="商品分区">
            <el-select
              class="handle-input"
              v-model="search.plural"
              placeholder="商品分区"
              clearable
              @change="getData()"
            >
              <el-option
                v-for="item in partitionList"
                :key="item.id"
                :label="item.pluralName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select
              class="handle-input"
              v-model="search.commodityClassifyLevel1"
              placeholder="商品分类"
              clearable
              @change="getData()"
            >
              <el-option
                v-for="item in classifyList"
                :key="item.id"
                :label="item.classifyName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select
              class="handle-input"
              v-model="search.audit"
              placeholder="审核状态"
              clearable
              @change="getData()"
            >
              <el-option
                v-for="item in auditStatusList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商户名称">
            <el-input
              v-model="search.merchantName"
              placeholder="商户名称"
              class="handle-input"
            />
          </el-form-item>
          <el-form-item label="上架时间">
            <el-date-picker
              v-model="search.time"
              type="datetime"
              placeholder="上架时间"
              @change="getData()"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="getData()"
              >搜索</el-button
            >
            <el-button type="primary" icon="el-icon-lx-add" @click="showBox()"
              >添加商品</el-button
            >
            <el-button type="primary" @click="handleAllUp()"
              >一键上架</el-button
            >
            <el-button type="primary" @click="handleAllDown()"
              >一键下架</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        :row-style="{ height: '80px' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="商品ID"></el-table-column>
        <el-table-column prop="name" label="商品名称"></el-table-column>
        <el-table-column prop="classifyPic" label="展示图片">
          <template #default="scope"
            ><el-image
              class="table-td-thumb"
              :src="scope.row.showPic"
              fit="cover"
          /></template>
        </el-table-column>
        <el-table-column
          prop="commodityClassifyLevel1Name"
          label="商品分类"
        ></el-table-column>
        <el-table-column prop="pluralName" label="商品分区"></el-table-column>
        <el-table-column prop="marketMoney" label="市场价"></el-table-column>
        <el-table-column prop="money" label="单价"></el-table-column>
        <el-table-column prop="merchantName" label="商户名称"></el-table-column>
        <el-table-column label="让利比率" align="center" width="100">
          <template #default="scope">
            <span>{{ formatRatio(scope.row.offerDiscountsRatio) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品标签" align="center" width="150">
          <template #default="scope">
            <div style="display: flex; flex-wrap: wrap; gap: 5px">
              <el-tag v-if="scope.row.isTj == 1" size="small" type="warning"
                >推荐</el-tag
              >
              <el-tag v-if="scope.row.isBp == 1" size="small" type="danger"
                >爆品</el-tag
              >
              <el-tag v-if="scope.row.isTm == 1" size="small" type="success"
                >特卖</el-tag
              >
              <el-tag v-if="scope.row.isZd == 1" size="small" type="primary"
                >主打</el-tag
              >
              <el-tag v-if="scope.row.isZx == 1" size="small" type="info"
                >甄选</el-tag
              >
              <el-tag v-if="scope.row.isQuota == 1" size="small">限购</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="商品状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status == '0'" type="success">上架</el-tag>
            <el-tag v-else type="danger">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="auditTime"
          label="审核时间"
          :formatter="dateFormat"
        ></el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button type="text" class="green" @click="handleCheak(scope.row)"
              >查看</el-button
            >
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" @click="handleState(scope.row)">{{
              scope.row.status == 0 ? "下架" : "上架"
            }}</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >

            <el-button
              type="text"
              v-if="scope.row.audit == 0"
              @click="handleAudit(scope.row)"
              >审核</el-button
            >
            <el-button type="text" v-if="scope.row.audit == 1"
              >已同意</el-button
            >
            <el-button type="text" v-if="scope.row.audit == 2"
              >已拒绝</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <CommodityDialog
      v-model:visible="showAddUser"
      :form-data="list"
      :is-edit="isChange == 0"
      :partition-list="partitionList"
      :classify-list="classifyList"
      :disabled="isDisabled"
      merchant-id="10"
      @confirm="handleDialogConfirm"
    />
    <!-- 发货信息 -->
    <el-dialog title="发货信息" v-model="show_audit" width="30%">
      <el-form ref="form" label-width="100px">
        <el-form-item label="拒绝原因"
          ><el-input disabled v-model="form.auditReason"
        /></el-form-item>
        <el-form-item label="赠送积分"
          ><el-input disabled v-model="form.gainIntegral"
        /></el-form-item>
        <el-form-item label="推荐人积分"
          ><el-input v-model="form.gainShareIntegral"
        /></el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirm_audit(2)">拒绝</el-button>
          <el-button type="primary" @click="confirm_audit(1)">同意</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  commodityList,
  commodityUp,
  commodityEdit,
  commodityDel,
  commodityAdd,
} from "../../api/zyMall";
import { api } from "../../api/index";
import { formatDate } from "../../common/data";
import CommodityDialog from "./components/CommodityDialog.vue";
import moment from "moment";
export default {
  inject: ["reload"],
  name: "basetable",
  components: { CommodityDialog },
  filters: {
    formatDate(time) {
      time = time * 1000;
      let date = new Date(time);
      console.log(new Date(time));
      return formatDate(date, "yyyy-MM-dd hh:mm");
    },
  },
  data() {
    return {
      username: localStorage.getItem("ms_username"),
      query: { pageNo: 1 },
      search: {},
      tableData: [],
      showAddUser: false,
      pageTotal: 0,
      list: {},
      isChange: "",
      picList: [],
      isDisabled: false,

      partitionList: [], // 分区列表
      classifyList: [], // 分类列表
      auditStatusList: [
        { name: "待审核", id: 0 },
        { name: "已通过", id: 1 },
        { name: "已拒绝", id: 2 },
      ],
      // 审核弹窗
      show_audit: false,
      form: {},
      selectedList: [],
    };
  },
  created() {
    this.getData();
    this.getFilter();
  },
  mounted() {},
  methods: {
    dateFormat: function (row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    dataFilter(data) {
      if (data == undefined) {
        return "";
      }
      return moment(data).format("YYYY-MM-DD");
    },
    joinpic(item) {
      return `https://mall.xiyibaomall.com/imgs/${item}`;
    },
    // 格式化让利比率显示
    formatRatio(ratio) {
      if (ratio == null || ratio == undefined || ratio == 0) {
        return "-";
      }
      return `${(ratio * 100).toFixed(0)}%`;
    },
    // 获取分类列表
    getData() {
      console.log();
      commodityList({
        limit: 10,
        offset: this.query.pageNo,
        name: this.search.name,
        audit: this.search.audit,
        plural: this.search.plural,
        merchantName: this.search.merchantName,
        auditTime: this.dataFilter(this.search.time),
        commodityClassifyLevel1: this.search.commodityClassifyLevel1,
      }).then((res) => {
        this.tableData = res.data.rows;
        this.pageTotal = res.data.total;
      });
    },
    getFilter() {
      //获取分类列表
      api("/web/scc/pd", { classifyPid: 0 }).then((res) => {
        this.classifyList = res.data;
      });
      //获取分区列表
      api("/web/sep/sl", {}).then((res) => {
        this.partitionList = res.data;
      });
    },
    //显示编辑框
    showBox() {
      this.list = {};
      this.picList = [];
      this.showAddUser = true;
      this.isChange = 1;
      this.isDisabled = false;
    },

    // 处理对话框确认
    handleDialogConfirm(formData) {
      console.log(formData);
      const data = {
        ...formData,
        commodityClassifyLevel2: 0,
      };

      if (this.isChange == 1) {
        // 新增商品
        commodityAdd(data)
          .then((res) => {
            if (res.code === 2000) {
              this.$message.success("新增商品成功");
              this.showAddUser = false;
              // 使用 nextTick 确保对话框关闭后再清空数据和刷新
              this.$nextTick(() => {
                this.list = {};
                this.getData();
              });
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(() => {
            this.$message.error("操作失败，请重试");
          });
      } else {
        // 编辑商品
        commodityEdit(data)
          .then((res) => {
            if (res.code === 2000) {
              this.$message.success("修改商品成功");
              this.showAddUser = false;
              // 使用 nextTick 确保对话框关闭后再清空数据和刷新
              this.$nextTick(() => {
                this.list = {};
                this.getData();
              });
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(() => {
            this.$message.error("操作失败，请重试");
          });
      }
    },
    // 删除操作
    handleDelete(row) {
      this.$confirm("确定要删除吗？", "提示", { type: "warning" })
        .then(() => {
          commodityDel({ id: row.id }).then((res) => {
            if (res.code === 2000) {
              this.$message.success(res.message);
              this.getData();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {});
    },
    //查看操作
    handleCheak(row) {
      this.picList = [];
      this.isDisabled = true;
      this.showAddUser = true;
      this.isChange = 0;
      this.list = { ...row };
    },
    // 编辑操作
    handleEdit(row) {
      this.picList = [];
      this.list = { ...row };
      this.isDisabled = false;
      this.showAddUser = true;
      this.isChange = 0;
    },
    //上下架
    handleState(row) {
      this.$confirm("确定改变状态", "提示", { type: "warning" })
        .then(() => {
          commodityUp({ id: row.id, status: row.status == 0 ? "1" : "0" }).then(
            (res) => {
              if (res.code === 2000) {
                this.$message.success(res.message);
                this.getData();
              } else {
                this.$message.error(res.message);
              }
            },
          );
        })
        .catch(() => {});
    },

    handleSelectionChange(val) {
      console.log(val.map((item) => item.id));
      this.selectedList = val.map((item) => item.id);
    },

    handleAllUp() {
      this.$confirm("确定改变状态", "提示", { type: "warning" })
        .then(() => {
          api("/web/sc/ocr", {
            commodityClassifyLevel1: this.search.commodityClassifyLevel1,
            status: 0,
          }).then((res) => {
            if (res.code === 2000) {
              this.$message.success(res.message);
              this.getData();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {});
    },
    handleAllDown() {
      this.$confirm("确定改变状态", "提示", { type: "warning" })
        .then(() => {
          api("/web/sc/ocr", {
            commodityClassifyLevel1: this.search.commodityClassifyLevel1,
            status: 1,
          }).then((res) => {
            if (res.code === 2000) {
              this.$message.success(res.message);
              this.getData();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {});
    },
    handleAudit(row) {  
      this.form = row;
      this.show_audit = true;
    },
    confirm_audit(item) {
      api("/web/sc/audit", {
        audit: item,
        auditReason: this.form.auditReason,
        gainIntegral: this.form.gainIntegral,
        gainShareIntegral: this.form.gainShareIntegral,
        id: this.form.id,
      }).then((res) => {
        if (res.code === 2000) {
          this.$message.success(res.message);
          this.getData();
        } else {
          this.$message.error(res.message);
        }
      });
    },

    // 分页导航
    handlePageChange(val) {
      // console.log(val);
      this.query.pageNo = val;
      this.getData();
    },
  },
};
</script>
<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.green {
  color: #0ab618;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  height: 60px;
}
</style>
